<template>
  <el-drawer v-model="dialogVisible" :title="drawerType ? '新增电费记录' : '编辑电费记录'">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="150px"
      class="demo-ruleForm2"
    >
      <el-form-item label="抄表时间：" prop="date">
        <el-date-picker
          v-model="ruleForm.date"
          type="month"
          placeholder="请选择月份"
          format="YYYY-MM"
          value-format="YYYY-MM"
          @change="infoChange"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="本月用电量：" prop="electricity">
        <el-input type="number" v-model="ruleForm.electricity" placeholder="请输入本月用电量" />
      </el-form-item>
      <el-form-item label="当月电价：" prop="price">
        <el-input type="number" v-model="ruleForm.price" placeholder="请输入当月电价" />
      </el-form-item>
      <el-form-item label="本月电费：">
        <el-input type="number" v-model="money" disabled />
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <el-input v-model="ruleForm.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick, computed } from 'vue'
  import type { FormInstance } from 'element-plus'
  import {
    postElectricityRecordCreate,
    putElectricityRecordUpdate,
  } from '@/api/controller/electricity-record-controller/index'
  import { getSiteById } from '@/api/controller/site-controller/index'
  import { ElMessage } from 'element-plus'
  import { multiply, bignumber, number } from 'mathjs'
  const ruleFormRef = ref<FormInstance>()
  const drawerType = ref(true)
  const money = computed(() =>
    number(multiply(bignumber(ruleForm.value.electricity), bignumber(ruleForm.value.price))),
  )
  const ruleForm = ref({
    siteId: history.state.id,
    date: null,
    year: null,
    month: null,
    electricity: null,
    price: null,
    electricityFree: null,
    remark: null,
  })

  const rules = reactive({
    date: [{ required: true, message: '请选择月份', trigger: 'blur' }],
    electricity: [
      { required: true, message: '请输入本月用电量', trigger: 'blur' },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: '请输入大于或等于0的数字(最多2位小数)',
      },
    ],
    price: [
      { required: true, message: '请输入本月电价', trigger: 'blur' },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: '请输入大于或等于0的数字(最多2位小数)',
      },
    ],
    remark: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
  })
  const dialogVisible = ref(false)
  //新增或修改
  const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        ruleForm.value.electricityFree = money.value
        delete ruleForm.value.date
        if (drawerType.value) {
          const result = await postElectricityRecordCreate(ruleForm.value, { loading: true })
          if (result.code === 200) {
            dialogVisible.value = false
            await emit('getData')
            ElMessage.success('添加成功')
          }
        } else {
          const result = await putElectricityRecordUpdate(ruleForm.value, { loading: true })
          if (result.code === 200) {
            dialogVisible.value = false
            await emit('getData')
            ElMessage.success('修改成功')
          }
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  const show = async (data) => {
    if (data) {
      ruleForm.value = JSON.parse(JSON.stringify(data))
      ruleForm.value.date = `${ruleForm.value.year}-${ruleForm.value.month}`
      drawerType.value = false
    } else {
      drawerType.value = true
      for (let key in ruleForm.value) {
        ruleForm.value[key] = null
      }
      ruleForm.value.siteId = history.state.id
      let res = await getSiteById({ id: ruleForm.value.siteId })
      ruleForm.value.price = res.data.price
    }
    dialogVisible.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }
  const infoChange = (val) => {
    ruleForm.value.year = val.split('-')[0] * 1
    ruleForm.value.month = val.split('-')[1] * 1
  }
  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>
